<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户积分变动管理
 *
 * @icon fa fa-circle-o
 */
class UserPointsLog extends Backend
{

    /**
     * UserPointsLog模型对象
     * @var \app\common\model\UserPointsLog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\UserPointsLog;
        $this->view->assign("typeList", $this->model->getTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['admin','adminuser','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->fee = fixNum($row->fee);
                $row->num = fixNum($row->num);
                $row->before = fixNum($row->before);
                $row->after = fixNum($row->after);
                $row->getRelation('admin')->visible(['username']);
				$row->getRelation('user')->visible(['username']);
				$row->getRelation('adminuser')->visible(['username']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function release(){
        $this->model = new \app\common\model\ReleasePointLog();

        if (false === $this->request->isPost()) {
            //获取用户总积分和总宝豆
            $total = \app\common\model\User::where('status', 'normal')->where('points','gt',0)->where('cargo_value','egt',0)->field('sum(points) as points,sum(cargo_value) as speed')->find();

            $this->view->assign('total_points',$total['points']);
            $this->view->assign('total_speed',$total['speed']);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            //用户最大可用宝豆=用户积分*config('site.transfer_to_lvse_point_percent')
            $percent = config('site.transfer_to_lvse_point_percent') / 100;
            //修正完的宝豆总数
            $total_speed = 0;

            //修正完宝豆的用户数据
            $user_list = [];
            //获取积分大于0的用户
            \app\common\model\User::where('status', 'normal')->where('points','gt',0)->where('cargo_value','egt',0)->chunk(100, function($users) use(&$user_list, $percent, &$total_speed){

                foreach ($users as $user) {
                    $point_plus = $user['points'] * $percent;
                    $max_speed = $point_plus > $user['cargo_value'] ? $user['cargo_value'] : $point_plus;
                    $total_speed += $max_speed;
                    $user_list[$user['id']] = [
                        'points' => $user['points'],
                        'point_plus' => $point_plus,
                        'cargo_value' => $user['cargo_value'],
                        'max_speed' => $max_speed,
                    ];
                }
            });

            $fee = 0;
            $sn = $this->model->id;
            $total_points_speed = $params['total_points'] + $total_speed;
            if($total_points_speed <= 0){
                Db::rollback();
                $this->error('总积分和总宝豆不能小于等于0');
            }
            //更新用户积分和宝豆
            foreach($user_list as $user_id => $user){
                $points = $params['points'] * ($user['points'] + $user['max_speed']) / $total_points_speed;
                if($points <= 0){
                    Db::rollback();
                    $this->error('用户获得绿色积分不能小于等于0');
                }
                // echo 'percent:' . (($user['points'] + $user['max_speed']) / $total_points_speed) . PHP_EOL;
                // echo 'points:' . $user['points'] . PHP_EOL;
                // echo 'point_plus:' . $user['point_plus'] . PHP_EOL;
                // echo 'cargo_value:' . $user['cargo_value'] . PHP_EOL;
                // echo 'max_speed:' . $user['max_speed'] . PHP_EOL;
                // echo 'new_points:' . $points . PHP_EOL;
                \think\Log::info('user_points:' . $user['points']);
                \think\Log::info('percent:' . $percent);
                \think\Log::info('cargo_value:' . $user['cargo_value']);
                \think\Log::info('max_speed:' . $user['max_speed']);
                \think\Log::info('new_points:' . $points);
                if($user['points'] < $points){
                    \think\Log::error('user_points:' . $user['points']);
                    \think\Log::error('new_points:' . $points);
                }
                \think\Log::info('another==================');

                //增加用户的绿色积分
                \app\common\model\User::activity_points(1, $sn, $points, $user_id, '转化');
                //减少用户的积分                
                \app\common\model\User::points(2, $sn, $fee, -$points, $user_id, '转化');
            }
            // echo 'total_points_speed:' . $total_points_speed . PHP_EOL;

            // var_dump($user_list);die;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

}
